package com.hushan.elevator.websocket.server;
import cn.hutool.core.util.URLUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Data
@ServerEndpoint("/websocket/{id}")
@Slf4j
public class WebSocketServer {
    public static CopyOnWriteArraySet<WebSocketServer> sessionSet = new CopyOnWriteArraySet<>();
    // connected client session
    private Session session;
    private String id;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) throws Exception {
        log.info("web {} connect", id);
        String queryString = session.getRequestURI().getQuery();
        String params =  URLUtil.decode(queryString, StandardCharsets.UTF_8);
        this.session = session;
        this.id = id;
        sessionSet.add(this);
    }

    @OnClose
    public void onClose() {
        log.info("web {} close", id);
        sessionSet.remove(this);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("id") String id) {
        log.warn("web {} error {}", id, error.toString());
        if (sessionSet.remove(this)) {
            error.printStackTrace();
        }
    }

    // receive msg from web
    // to device
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        DeviceSocketServer.sendMessage(this.id, message);
   }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public synchronized static void sendMessage(@PathParam("id") String id, String message) throws IOException {
        for (WebSocketServer ws : sessionSet) {
            if (ws.id.equals(id)) {
                ws.sendMessage(message);
            }
        }
    }
}